//
//  RetrievePasswordViewController.m
//  EatDistribute
//
//  Created by ---☆渴望☆--- on 16/1/13.
//  Copyright © 2016年 Haricot. All rights reserved.
//

#import "ForgetViewController.h"
#import "MyTools.h"
#import "LoginViewController.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "UIView+Toast.h"
@interface ForgetViewController ()<UITextFieldDelegate>

@end

@implementation ForgetViewController
{
    UITextField  * _textField;
    UITextField  * _mobileField;
    NSTimer * _time;
    int j;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //self.view.backgroundColor =UIColorFromRGB(MYGreen);
    
    self.navigationItem.title =@"登录";
    
    //    self.view.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"denglu_bg.png"]];
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    imageview.image = [UIImage imageNamed:@"denglu_bg.png"];
    [self.view addSubview:imageview];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate =(id)self;
    [self creatUI];
    
}

- (void)creatUI
{
    NSArray * array = @[@"请输入手机号",@"请输入验证码",@"设置新密码",@"再次输入密码"];
    NSArray *picArr = @[@"手机号码图标",@"验证码图标",@"设置密码图标",@"再次输入密码图标"];
    for (int i = 0; i < array.count; i++) {
        _textField =[[UITextField alloc]initWithFrame:CGRectMake(WIDTH / 5, HEIGHT*(120+70*i)/667, WIDTH - WIDTH / 7.5, HEIGHT*40/667)];
        
        UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:picArr[i]]];
        image.frame = CGRectMake(WIDTH/15, HEIGHT*(120+70*i)/667, HEIGHT *40/667, HEIGHT *40/667);
        [self.view addSubview:image];
        
        
        _textField.borderStyle     = UITextBorderStyleNone;
        _textField.placeholder     = array[i];
        _textField.secureTextEntry = NO;
        _textField.tag             = 100 + i;
        _textField.font            = [UIFont systemFontOfSize:15];
        [self.view addSubview:_textField];
        if (_textField.tag == 100) {
            _textField.keyboardType = UIKeyboardTypeNumberPad;
        }
        if (_textField.tag == 102 | _textField.tag == 103) {
            _textField.secureTextEntry = YES;
        }
        UIView *lineview = [[UIView alloc]initWithFrame:CGRectMake(WIDTH / 15, HEIGHT*(160+70*i)/667, WIDTH - WIDTH / 7.5, 1)];
        lineview.backgroundColor = UIColorFromRGB(MYGray);
        [self.view addSubview:lineview];
    }
    
    _textField.delegate = self;
    
    
    
    
    //获取验证码
    UIButton * buttonObtain =[[UIButton alloc]initWithFrame:CGRectMake(WIDTH *0.7,HEIGHT *185/667, WIDTH*0.25, 40)];
    buttonObtain.backgroundColor =UIColorFromRGB(MYColor);
    [buttonObtain setTitle:@"获取验证码" forState:UIControlStateNormal];
    [buttonObtain addTarget:self action:@selector(buttonObtainClick) forControlEvents:UIControlEventTouchUpInside];
    buttonObtain.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:15];
    buttonObtain.layer.cornerRadius = 5;
    buttonObtain.tag = 12;
    buttonObtain.layer.masksToBounds=YES;
    [self.view addSubview:buttonObtain];
    
    //立即找回密码
    UIButton * buttonRetrieve =[[UIButton alloc]initWithFrame:CGRectMake(WIDTH / 8, HEIGHT*400/667, WIDTH - WIDTH / 4, 40)];
    buttonRetrieve.backgroundColor =UIColorFromRGB(MYColor);
    [buttonRetrieve setTitle:@"立即找回" forState:UIControlStateNormal];
    [buttonRetrieve addTarget:self action:@selector(buttonRetrieveClick) forControlEvents:UIControlEventTouchUpInside];
    buttonRetrieve.layer.cornerRadius = 5;
    buttonRetrieve.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:15];
    buttonRetrieve.layer.masksToBounds = YES;
    [self.view addSubview:buttonRetrieve];
    
    //返回登录页
    UIButton * buttonReturn =[[UIButton alloc]initWithFrame:CGRectMake(WIDTH / 8, HEIGHT*450/667, WIDTH - WIDTH / 4, 40)];
    buttonReturn.backgroundColor =UIColorFromRGB(MYColor);
    [buttonReturn setTitle:@"返回登录页" forState:UIControlStateNormal];
    [buttonReturn addTarget:self action:@selector(buttonReturnClick) forControlEvents:UIControlEventTouchUpInside];
    buttonReturn.layer.cornerRadius = 5;
    buttonReturn.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:15];
    buttonReturn.layer.masksToBounds=YES;
    [self.view addSubview:buttonReturn];
    
    
    //手势
    UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tgrClick:)];
    
    [self.view addGestureRecognizer:tgr];
    
}

- (void)tgrClick:(UITapGestureRecognizer *)tgr{
    
    UITextField *purseLab1 = (id)[self.view viewWithTag:100];
    UITextField *purseLab2 = (id)[self.view viewWithTag:101];
    UITextField *purseLab3 = (id)[self.view viewWithTag:102];
    UITextField *purseLab4 = (id)[self.view viewWithTag:103];
    //放弃第一响应
    [purseLab1 resignFirstResponder];
    [purseLab2 resignFirstResponder];
    [purseLab3 resignFirstResponder];
    [purseLab4 resignFirstResponder];
}
- (void)buttonObtainClick
{
    
    UITextField *mobileTextField = (id)[self.view viewWithTag:100];
    NSLog(@"获取验证码");
  //  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:mobileTextField.text forKey:@"mobile"];
    [dic setObject:@"true" forKey:@"is_mi"];
    
    NSLog(@"dic %@",dic);
    
    [manager POST:@"http://www.xsy777.com/ucenter/verify/sendverifydo.html" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSString * str = [NSString stringWithFormat:@"%@",[dic1 objectForKey:@"status"]];
        if ([str isEqualToString:@"1"]) {
            
  //          [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self.view makeToast:dic1[@"info"] duration:0.5 position:CSToastPositionCenter];
            NSLog(@"%@",dic1[@"info"]);
            NSLog(@"%@",dic1[@"code"]);
            
            j = 59;
            UITextField *nametextFied = (id)[self.view viewWithTag:100];
            if (!((nametextFied.text.length == 11) && [[nametextFied.text substringToIndex:1] isEqualToString:@"1"])){
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请输入正确的手机号" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                _time = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(page:) userInfo:alert repeats:YES];
                [alert show];
                return;
            }else{
                UIButton *but = (id)[self.view viewWithTag:12];
                [but setTitle:@"已发送" forState:UIControlStateNormal];
                [but setBackgroundColor:[UIColor lightGrayColor]];
                but.userInteractionEnabled = NO;
                _time = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timer:) userInfo:nil repeats:YES];
            }
            
        }else{
   //         [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self.view makeToast:dic1[@"info"] duration:0.5 position:CSToastPositionCenter];
            NSLog(@"%@",dic1[@"info"]);
        }
    }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
   //           [MBProgressHUD hideHUDForView:self.view animated:YES];
              [self.view makeToast:@"获取验证码失败" duration:0.5 position:CSToastPositionCenter];
              NSLog(@"%@",error.description);
              
          }];
}

- (void)timer:(NSTimer *)tim{
    UIButton *but = (id)[self.view viewWithTag:12];
    j = j - 1;
    if (j == 0) {
        j = 59;
        [but setTitle:@"获取验证码" forState:UIControlStateNormal];
        [but setBackgroundColor:UIColorFromRGB(MYColor)];
        but.userInteractionEnabled = YES;
        [_time invalidate];
        _time = nil;
        
    }else{
        NSString *str = [[NSString alloc]initWithFormat:@"%dS",j];
        [but setTitle:str forState:UIControlStateNormal];
        [but setBackgroundColor:[UIColor lightGrayColor]];
    }
}
- (void)page:(NSTimer*)theTimer{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:YES];
    promptAlert =NULL;
}


-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    CGFloat offset = self.view.frame.size.height - (textField.frame.origin.y + textField.frame.origin.y + 160);
    if (offset <= 0) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.view.frame;
            frame.origin.y = offset;
            self.view.frame = frame;
        }];
    }
    return YES;
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = self.view.frame;
        frame.origin.y = 0.0;
        self.view.frame = frame;
    }];
    return YES;
}

- (void)buttonRetrieveClick
{
    NSLog(@"立即找回");
    UITextField *nametextFied = (id)[self.view viewWithTag:100];
    UITextField *codetextFied = (id)[self.view viewWithTag:101];
    UITextField *newregistertextFied = (id)[self.view viewWithTag:102];
    UITextField *tworegistertextFied = (id)[self.view viewWithTag:103];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    if ([nametextFied.text isEqualToString:@""]) {
        alert.title = @"手机号不能为空!";
        [alert show];
    }
    if ([codetextFied.text isEqualToString:@""]) {
        alert.title = @"验证码不能为空!";
        [alert show];
    }if ([newregistertextFied.text isEqualToString:@""]) {
        alert.title = @"请输入新密码!";
        [alert show];
    }if ([tworegistertextFied.text isEqualToString:@""]) {
        alert.title = @"请输入新密码!";
        [alert show];
    }if (![newregistertextFied.text isEqualToString:tworegistertextFied.text]){
        alert.title = @"密码输入不一致!";
        [alert show];
    }
    else{
        
        NSString *urlstr = @"http://hmyx.ijiaque.com/app/user/reset_pwd.html";
        //        NSDictionary *dic = @{@"reg_verify":codetextFied.text,
        //                              @"mobile":nametextFied.text,
        //                              @"password":newregistertextFied.text};
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:codetextFied.text forKey:@"reg_verify"];
        [dic setObject:nametextFied.text forKey:@"mobile"];
        [dic setObject:newregistertextFied.text forKey:@"password"];
        NSLog(@"===%@",dic);
        AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
  //      [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        manager.responseSerializer=[AFHTTPResponseSerializer serializer];
        [manager POST:urlstr parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
  //          [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            NSString *str = [NSString stringWithFormat:@"%@",[dic1 objectForKey:@"status"]];
            
            if ([str isEqualToString:@"1"]) {
                //                [MBProgressHUD hideHUDForView:self.view animated:YES];
                //                [self.view makeToast:dic1[@"info"] duration:0.5 position:CSToastPositionCenter];
                alert.title = [NSString stringWithFormat:@"%@,请重新登录",[dic1 objectForKey:@"info"]];
                [alert show];
                LoginViewController * loginVC =[[LoginViewController alloc]init];
                [self presentViewController:loginVC animated:YES completion:nil];
            }else {
                //                [MBProgressHUD hideHUDForView:self.view animated:YES];
                //                [self.view makeToast:dic1[@"info"] duration:0.5 position:CSToastPositionCenter];
                alert.title = @"请输入新密码!";
                [alert show];
            }
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
            NSLog(@"=====>%@",error);
            alert.title = @"网络连接失败";
            [alert show];
        }];
        
    }
}

- (void)buttonReturnClick
{
    LoginViewController * loginVC =[[LoginViewController alloc]init];
    [self presentViewController:loginVC animated:YES completion:nil];
}

//- (void)tgrClick:(UITapGestureRecognizer *)tgr
//{
//    //[_textField resignFirstResponder];
//    UITextField * textField1 = (id)[self.view viewWithTag:250];
//    UITextField * textField2 = (id)[self.view viewWithTag:251];
//    UITextField * textField3 = (id)[self.view viewWithTag:252];
//    UITextField * textField4 = (id)[self.view viewWithTag:253];
//    [textField1 resignFirstResponder];
//    [textField2 resignFirstResponder];
//    [textField3 resignFirstResponder];
//    [textField4 resignFirstResponder];
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
